import axios from 'axios'
import { Message } from '@arco-design/web-vue'
import { h } from 'vue'
import { IconFaceFrownFill } from '@arco-design/web-vue/dist/arco-vue-icon'
import router from '@/router'
import { useUserStore } from '@/store'
import qs from 'qs'
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 50000,
  withCredentials: true, // 保证携带 Cookie
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  },
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (!config.params) {
      config.params = {};
    }
    config.params['fro_source'] = 1; 
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 如果响应的 code 不等于 200，抛出异常
    const useStore=useUserStore()
    if (response.data.code !== 200 ) {
      let errorMessage = response?.data?.msg || '请求失败'
      errorMessage = errorMessage.replace(/\[.*?\]/g, '').trim()
      Message.error({
        content: errorMessage,
        icon: () => h(IconFaceFrownFill),
      })
      if(errorMessage.includes('重新登录')){//cookie过期后 后端返回的错误 code ==0 msg ：请重新登录
        useStore.clearToken()
        router.push({ name: 'login' })
      }else{
        return Promise.reject(new Error(errorMessage))
      }
    }else{
      return response.data
    }
  },
  (error) => {
    // 错误处理
    let errorMessage = error.response?.data?.msg || '后端接口异常'
    errorMessage = errorMessage.replace(/\[.*?\]/g, '').trim()
    Message.error({
      content: errorMessage,
      icon: () => h(IconFaceFrownFill),
    })
    return Promise.reject(error)
  }
)

export const request = (config) => {
  if (config.headers && config.headers['Content-Type'] === 'multipart/form-data') {
    return service(config);
  }else if(config.requestType=='special'){//处理对象数组的参数提交请求
    config.data = qs.stringify(config.data, {
      allowDots: false, // 不使用点号分隔符
      indices: config.indices||false,   // 防止数组变成 `left_area_arr[0].tw` 这种格式
      encode: true,
    });
    return service(config);
  }else{//一般请求参数处理
    if (config.data) {
      const params = new URLSearchParams();
      for (const key in config.data) {
        if (Array.isArray(config.data[key])) {
          config.data[key].forEach((item, index) => {
            params.append(`${key}[${index}]`, item);
          });
        } else {
          params.append(key, config.data[key]);
        }
      }
      config.data = params.toString();
    }
  
    return service(config);
  }
  }

export default request
